package com.ruoyi.web.interceptor;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysServerRegiste;
import com.ruoyi.system.service.ISysServerRegisteService;
import com.ruoyi.web.util.BasicAuthUtil;
import com.ruoyi.web.util.RedisKeys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author ：吉金武
 * @ClassName AccessTokenInterceptor
 * @date ：2024/5/2 - 22:00
 * @version: V1.0
 * @slogan: 天下风云出我辈，一入代码岁月催
 * @description:
 **/
@Component
public class AccessTokenInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private ISysServerRegisteService sysServerRegisteService;

    @Autowired
    private RedisCache redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)){
            resultError("请求非法: this is header Authorization Basic is null !", response);
            return false;
       }
        String basic1 = BasicAuthUtil.getBasic(authorization);
        String[] basicUsernameAndPassword = BasicAuthUtil.getBasicUsernameAndPassword(basic1);
        String systemName = "";
        String companyName = "";
        if (basicUsernameAndPassword.length > 1){
            systemName = basicUsernameAndPassword[0];
            companyName = basicUsernameAndPassword[1];
        }
        SysServerRegiste sysServerRegisteEntity = sysServerRegisteService.findBySystemNameAndCompanyName(systemName, companyName);
        if (sysServerRegisteEntity == null){
            resultError(" 请求没有权限", response);
            return false;
        }
        String basic = BasicAuthUtil.encodeCredentials(sysServerRegisteEntity.getSystemName(), sysServerRegisteEntity.getCompanyName());
        if (!basic.equals(BasicAuthUtil.getBasic(authorization))){
            resultError("请求非法：Authorization认证失败", response);
            return false;
        }

        String accessToken = request.getHeader("accessToken");
        if (StringUtils.isEmpty(accessToken)){
            resultError(" this is header accessToken is null !", response);
            return false;
        }
        String redisAccessToken = redisUtils.getCacheObject(RedisKeys.getAccessTokenKey(sysServerRegisteEntity.getAppId(), sysServerRegisteEntity.getAppSecret()));
        if (StringUtils.isEmpty(redisAccessToken)) {
            // accessToken 已经失效!
            resultError(" this is  accessToken Invalid ", response);
            return false;
        }

        return true;
    }

    /**
     * 返回错误提示
     * @param errorMsg
     * @param response
     * @date  2019/12/3 0003 21:58
     * @return void
     */
    public void resultError(String errorMsg, HttpServletResponse response) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.write("{\"code\": \"" +401 + "\", \"errorMsg\": " + errorMsg + "}");
    }

}

